/*
  Motor.cpp- Library for controlling two motors with a ardumoto shield.
  *NOTE* Used code given by sparkfun to base library off of.
  created by Matthew Hughes, febuary 18, 2014.
  Note- I am not responsible for any damage caused by this code. so yeah don't sue me or anything
  that'd be nice if you didn't sue me.Thaaaannnkkkssssss...
  Released into the public domain.
*/
#include "Arduino.h"
#include "Motor.h"

Motor::Motor(int aval)
{
    pwm_a = 3;   //PWM control for motor outputs 1 and 2 is on digital pin 3
    pwm_b = 11;  //PWM control for motor outputs 3 and 4 is on digital pin 11
    dir_a = 12;  //direction control for motor outputs 1 and 2 is on digital pin 12
    dir_b = 13;  //direction control for motor outputs 3 and 4 is on digital pin 13
    val = aval;     //value for fade
}
void Motor::setup()
{
    pinMode(pwm_a, OUTPUT);  //Set control pins to be outputs
    pinMode(pwm_b, OUTPUT);
    pinMode(dir_a, OUTPUT);
    pinMode(dir_b, OUTPUT);
}
void Motor::direct(int d_a,int d_b){
    if(d_a==1)//backwards
        digitalWrite(dir_a,HIGH);
    else
        digitalWrite(dir_a,LOW);
    if(d_b==1)
        digitalWrite(dir_b,HIGH);
    else
        digitalWrite(dir_b,LOW);
    
}
void Motor::speed(int s, int parallel)
{
    if(parallel==0){//0 means off
        if( s > 0){
            digitalWrite(dir_a,LOW);
            analogWrite(pwm_a,s);
        }else{
            digitalWrite(dir_a,HIGH);
            analogWrite(pwm_a,abs(s));
        }
    }else{
        if( s > 0){
            digitalWrite(dir_a,LOW);
            digitalWrite(dir_b,LOW);
            analogWrite(pwm_a,s);
            analogWrite(pwm_a,s);
        }else{
            digitalWrite(dir_a,HIGH);
            digitalWrite(dir_b,HIGH);
            analogWrite(pwm_a,abs(s));
            analogWrite(pwm_b,abs(s));
            
        }
    }
}
void Motor::Fadein()
{
    // fade in from min to max in increments of 5 points:
    for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5)
    {
        // sets the value (range from 0 to 255):
        analogWrite(pwm_b, fadeValue);
        analogWrite(pwm_a, fadeValue);
        // wait for 30 milliseconds to see the dimming effect
        delay(30);
    }
}
void Motor::Fadeout()
{
    for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5)
    {
        // sets the value (range from 0 to 255):
        analogWrite(pwm_b, fadeValue);
        analogWrite(pwm_a, fadeValue);
        // wait for 30 milliseconds to see the dimming effect
        delay(30);
    }
}
void Motor::stop_A()
{
    analogWrite(pwm_a, 0);    //set both motors to run at 0% duty cycle (stop)
}
void Motor::stop_B()
{
    analogWrite(pwm_b, 0);    //set both motors to run at 0% duty cycle (stop)
}

void Motor::stop_AB()
{
    analogWrite(pwm_a, 0);    //set both motors to run at 0% duty cycle (stop)
    analogWrite(pwm_b, 0);    //set both motors to run at 0% duty cycle (stop)
}

Motor::~Motor(){}
